#include "util.h"
#include "ff.h"


/* 将Unicode转换为UTF8编码 */
int uni2utf8(wchar_t chr, uint8_t *buf)
{
    int cnt;
    if (chr < 0x80U) /* ascii */
    {
        buf[0] = (uint8_t)chr;
        cnt = 1;
    }
    else if (chr < 0x800U) /* 2byte */
    {
        buf[0] = (0xC0U | ((chr >> 6U) & 0x1FU));
        buf[1] = (0x80U) | (chr & 0x3FU);
        cnt = 2;
    }
    else /* 3byte */
    {
        buf[0] = (0xE0U) | ((chr >> (6*2U)) & 0xFU);
        buf[1] = (0x80U) | ((chr >> (6U)) & 0x3FU);
        buf[2] = (0x80U) | (chr & 0x3FU);
        cnt = 3;
    }
    
    return cnt;
}

/**
  * @brief  单字节字符串转化为宽字符串
  */
wchar_t *str2wstr(wchar_t *buf, const char *charArr)
{
    int index = 0;
    while (charArr[index])
    {
        buf[index] = charArr[index];
        index++;
    }
    buf[index] = 0; /* '\0 */
    return buf;
}

/**
  * @brief  宽字符比较
  * @return 0 相等; != 0 *ptr1 - *ptr2
  */
int wstrncmp(wchar_t *s1, wchar_t *s2, int n)
{
    int diff;
    for (int i = 0; i < n; i++)
    {
        diff = s1[i] - s2[i];
        if (diff)
        {
            return diff;
        }
    }
    return 0;
}

wchar_t *wtoUpper(wchar_t *s)
{
    int code = s[0];
    for (int i = 0; s[i] != 0; i++)
    {
        if (code <= 'z' && code >= 'a')
        {
            s[i] -= 'a' - 'A';
        }
        code = s[++i];
    }
    return s;
}

wchar_t *wstrcpy(wchar_t *dest, const wchar_t *src)
{
    wchar_t *ret = dest;
    while (*src)
    {
        *dest++ = *src++;
    }
    return ret;
}

wchar_t *getPathExtName(wchar_t *buf, wchar_t *path)
{
    if ((path == NULL) || (buf == NULL)) return NULL;
    if (path[0] == 0) return NULL;

    int index = 0;
    while (path[index]) { index++; }
    index--;
    while ((path[index] != L'.') && (index >= 0)) { index--; }
    index++;
    if (index == 0)
    {
        buf[0] = 0;
        return buf;
    }
    else
    {
        return wstrcpy(buf, &path[index]);
    }
}